package com.zha.config;

import cn.hutool.core.util.ObjectUtil;
import com.zha.constant.AuthConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Title: 只有光头才能变强
 * @Author: 炸炸
 * @Date: 2024/12/11 16:09
 * feign拦截器
 */
@Component
public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取上一次请求的请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ObjectUtil.isNotNull(requestAttributes)){
            // 获取请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            // 判断是否有值
            if (ObjectUtil.isNotNull(request)){
                // 获取上一次请求对象头中的Authorization值
                String authorization = request.getHeader(AuthConstants.AUTHORIZATION);
                // 判断是否有值
                if (StringUtils.hasText(authorization) && authorization.startsWith(AuthConstants.BEARER)){
                    // 获取请求的token值
                    String token = authorization.replace(AuthConstants.BEARER, "");
                    // 判断是否有值
                    if (StringUtils.hasText(token)){
                        // 将上一个请求头中的token传递到下一个请求对象的请求头中
                        requestTemplate.header(AuthConstants.AUTHORIZATION, AuthConstants.BEARER + token);
                        return;
                    }
                }
            }
        }
        // 给requestTemplate添加一个固定的TOKEN值
        requestTemplate.header(AuthConstants.AUTHORIZATION, AuthConstants.BEARER + "3d22843f-4cd5-456a-8397-8b5cfe6ff845");
    }
}
